import os,tempfile,uuid,shutil,commands
import socket

import time
import logging
log = logging.getLogger(__name__)

class IClientMaker(object):
    """
    This is the abstract interface that VMManager calls to produce the userdata/client to give the VMs.
    
    @author Yushu Yao
    @version 0.1
    """

    def __init__(self,clienttype):
        self.clienttype=clienttype

    def makeClient(self,vm):
        """will return a dict {clientuuid->path to a userdata file}"""
        raise NotImplementedError

    def expireClient(self,clientuuid):
        raise NotImplementedError

import pickle

class CentOS5_Puppet_ClientMaker(IClientMaker):
    def __init__(self):
        super(CentOS5_Puppet_ClientMaker, self).__init__("centos5_puppet")

        #Map of "clientuuid->pathToTarredBase64file
        self.__clients={}

        self.__templatedir="/usr/local/turbogears/crvclient"

    def __del__(self):
        for icl in self.__clients.keys():
            self.expireClient(icl)
            
    def makeClient(self,vm):
        """will return a dict {clientuuid->path to a userdata file}"""
        myuuid=str(uuid.uuid4())
        workdir=tempfile.gettempdir()+"/"+myuuid
        clientdir=workdir+"/crvclient"
        tarfile=workdir+"/client.tgz"
        base64file=workdir+".tgz.base64"
        
        #FIXME: assuming uuid never duplicates
        os.makedirs(workdir,0700)

        shutil.copytree(self.__templatedir,clientdir)

        #create the python info for this vm
        ouf=open(clientdir+"/"+"values.pickle","w")
        pickle.dump(vm.VM_ID,ouf)
        pickle.dump("http://%s:8080/status/"%socket.gethostbyname(socket.gethostname()),ouf)
        pickle.dump(socket.gethostname(),ouf)
        ouf.close()

        #tar and base64 the dir to a file
        cmdstr="tar czf %s -C %s %s"%(tarfile,workdir,"crvclient")
        (status,output)=commands.getstatusoutput(cmdstr)
        if status!=0:
            raise RuntimeError("CentOS5_Puppet_ClientMaker::makeClient:: can't execute %s,output=%s, status=%d"%(cmdstr,output,status))
        cmdstr="base64 -w 0 %s"%tarfile
        (status,output)=commands.getstatusoutput(cmdstr)
        if status!=0:
            raise RuntimeError("CentOS5_Puppet_ClientMaker::makeClient:: can't execute %s,output=%s, status=%d"%(cmdstr,output,status))
        ouf=open(base64file,"w")
        ouf.write(output)
        ouf.close()

        #put it to my collection and hand it back
        self.__clients[myuuid]=base64file

        #remove workdir
        shutil.rmtree(workdir,ignore_errors=True)

        return (myuuid,base64file)
        
    def expireClient(self,icl):
        os.remove(self.__clients[icl])
        self.__clients.pop(icl)


